import { Card, Form, Breadcrumb, Input, Space, Button, Select, Radio, Upload } from "antd"
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams, useNavigate } from 'react-router-dom'
import { useEffect, useRef, useState } from "react"
import { useStore } from '@/store'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { http } from '@/utils'

const { Option } = Select

const Publish = () => {
  // 最大图片数量
  const [maxCount, setMaxCount] = useState('')
  // 声明一个暂存仓库
  const fileListRef = useRef([])
  // 图片数据管理
  const [fileList, setFileList] = useState([])

  const { channelStore } = useStore()

  const [params] = useSearchParams()
  const articleId = params.get('id')

  const [form] = Form.useForm()
  const navigate = useNavigate()

  const changeType = e => {
    const count = e.target.value
    setMaxCount(count)
    if (count === 1) {
      const firstImg = fileListRef.current[0]
      setFileList(!firstImg ? [] : [firstImg])
    } else if (count === 3) {
      setFileList(fileListRef.current)
    }
  }

  const onUploadChange = ({fileList}) => {
   const formatFileList = fileList.map(item => {
      if (item.response) {
        return {
          url: item.response.data.url
        }
      }
      return item
   })
    setFileList(formatFileList)
    fileListRef.current = formatFileList
  }

  const onFinish = async (values) => {
    const {type, ...res} = values
    const data = {
      ...res,
      cover: {
        type,
        images: fileList.map(item => item.url)
      },
    }
    if (articleId) {
      // 修改
      await http.put(`/mp/articles/${articleId}?draft=false`, data)
    } else {
      // 新增
      await http.post(`/mp/articles/?draft=false`, data)
    }
    navigate('/article')
  }

  useEffect(() => {
    async function getArticle() {
      const res = await http.get(`/mp/articles/${articleId}`)
      const { cover, ...formValue } = res.data
      // 动态设置表单数据
      form.setFieldsValue({ ...formValue, type: cover.type })
      // 处理图片数据格式
      const imgList = cover.images.map(item => ({ url: item }))

      setFileList(imgList)
      fileListRef.current = imgList
      setMaxCount(cover.type)
    }
    if (articleId) {
      getArticle()
    }
  }, [articleId])

  return (
    <div className="publish">
      <Card title={
        <Breadcrumb separator='>'>
          <Breadcrumb.Item>
            <Link to='/'> 首页 </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item> {articleId ? '修改文章' : '发布文章'} </Breadcrumb.Item>
        </Breadcrumb>
      }>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{content: ''}}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label='标题'
            name='title'
            rules={[{required: true, message: '请输入文章标题'}]}
          >
            <Input placeholder="请输入文章标题" style={{width: 400}}/>
          </Form.Item>
          <Form.Item
            label='频道'
            name='channel_id'
            rules={[{required: true, message: '请选择文章频道'}]}
          >
            <Select style={{ width: 400 }}>
              {channelStore.channelList.map(item => (
                <Option key={item.id} value={item.id}> {item.name} </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label='封面'
          >
            <Form.Item name='type'>
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {maxCount > 0 && (
              <Upload
                name='image'
                listType='picture-card'
                showUploadList
                onChange={onUploadChange}
                action="http://geek.itheima.net/v1_0/upload"
                maxCount={maxCount}
                multiple={maxCount > 1}
                fileList={fileList}
                className="avatar-uploader"
              >
                <div style={{marginTop: 8}}>
                  <PlusOutlined/>
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label='内容'
            name='content'
            rules={[{required: true, message: '请输入文章内容'}]}
          >
            <ReactQuill
              className='publish-quill'
              theme='snow'
              placeholder='请输入文章内容'
            ></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{offset: 4}}>
            <Space>
              <Button type="primary" htmlType="submit" size="large"> {articleId ? '修改文章' : '发布文章'} </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish